package com.tiennt.android.callnotes;

import java.util.ArrayList;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.tiennt.android.callnotes.db.DbAdapter;
import com.tiennt.android.callnotes.models.contentholders.SingleNote;
import com.tiennt.android.callnotes.models.listadapters.ListNotesByContactAdapter;
import com.tiennt.android.callnotes.utils.ProjectUtils;

public class ViewNotesByContactActivity extends Activity {
	private final String TAG = "ViewNotesByContactActivity";
	private final boolean DBG = true;
	public static final int REQUEST_ADD_NOTE = 1002;

	private String contactId;

	private ListView mListNotes;
	private ImageView imgvContactImage;
	private TextView tvContactName;
	private AdapterView.OnItemClickListener onListItemClick;
	ListNotesByContactAdapter mListAdapter;
	ActionBar mActionBar;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_view_notes_by_contact);

		mActionBar = getActionBar();
		mActionBar.setDisplayHomeAsUpEnabled(true);
		mActionBar.setTitle("");

		initialComponents();
	}

	private void initialComponents() {
		Bundle data = getIntent().getExtras();
		long temp = data.getLong(ProjectUtils.BUNDLEKEY_CONTACTID);
		contactId = temp + "";

		imgvContactImage = (ImageView) findViewById(R.id.imgvContactImage);
		imgvContactImage.setImageBitmap(BitmapFactory.decodeByteArray(
				getIntent().getByteArrayExtra(
						ProjectUtils.BUNDLEKEY_CONTACTPHOTO),
				0,
				getIntent().getByteArrayExtra(
						ProjectUtils.BUNDLEKEY_CONTACTPHOTO).length));

		tvContactName = (TextView) findViewById(R.id.tvContactName);
		tvContactName.setText(data
				.getString(ProjectUtils.BUNDLEKEY_CONTACTNAME));

		mActionBar.setTitle("All " + tvContactName.getText().toString().trim()
				+ "'s notes");

		mListNotes = (ListView) findViewById(R.id.lvNotesByContact);

		mListAdapter = new ListNotesByContactAdapter(this, getAllNotes());
		mListNotes.setAdapter(mListAdapter);

		mListNotes.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
		mListNotes.setMultiChoiceModeListener(new ModeCallback());

		if (mListAdapter.getCount() == 0) {
			((TextView) findViewById(R.id.tvNoAnyNote))
					.setVisibility(View.VISIBLE);
			mListNotes.setVisibility(View.GONE);
		} else {
			((TextView) findViewById(R.id.tvNoAnyNote))
					.setVisibility(View.GONE);
			mListNotes.setVisibility(View.VISIBLE);
		}

		onListItemClick = new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				// handleOnListItemClick(parent, view, position, id);
			}

		};

		mListNotes.setOnItemClickListener(onListItemClick);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (requestCode == REQUEST_ADD_NOTE) {
			if (resultCode == RESULT_OK) {
				log("RESULT");
				refreshListView();
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.view_notes_by_contact, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case android.R.id.home:
			// app icon in Action Bar clicked; go home
			setResult(RESULT_OK);
			this.finish();
			return true;
		case R.id.action_addnote:
			Intent intent2 = new Intent(this, AddNoteActivity.class);
			Bundle data = new Bundle();
			data.putString(ProjectUtils.BUNDLEKEY_CONTACTID, contactId);
			data.putString(ProjectUtils.BUNDLEKEY_CONTACTNAME, tvContactName
					.getText().toString());
			intent2.putExtras(data);
			startActivityForResult(intent2, REQUEST_ADD_NOTE);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private class ModeCallback implements ListView.MultiChoiceModeListener {

		public boolean onCreateActionMode(ActionMode mode, Menu menu) {
			MenuInflater inflater = getMenuInflater();
			inflater.inflate(R.menu.list_notes_select_menu, menu);
			mode.setTitle("Select Items");
			return true;
		}

		public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
			return true;
		}

		public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
			switch (item.getItemId()) {
			case R.id.delete:
				doDeleteNotes();
				mode.finish();
				break;
			default:

				break;
			}
			return true;
		}

		public void onDestroyActionMode(ActionMode mode) {
		}

		public void onItemCheckedStateChanged(ActionMode mode, int position,
				long id, boolean checked) {
			if (checked) {
				mListAdapter.setNewSelection(position);
			} else {
				mListAdapter.removeSelection(position);
			}

			final int checkedCount = mListNotes.getCheckedItemCount();
			switch (checkedCount) {
			case 0:
				mode.setSubtitle(null);
				break;
			case 1:
				mode.setSubtitle("One note selected");
				break;
			default:
				mode.setSubtitle("" + checkedCount + " notes selected");
				break;
			}
		}

	}

	private void doDeleteNotes() {
		DbAdapter dbAdapter = new DbAdapter(this);
		dbAdapter.open();

		ArrayList<Integer> selectedItem = mListAdapter
				.getCurrentCheckedPosition();
		for (int i : selectedItem) {
			SingleNote item = (SingleNote) mListNotes.getItemAtPosition(i);
			dbAdapter.deleteNotes(item.getId());
		}

		dbAdapter.close();
		refreshListView();

	}

	private ArrayList<SingleNote> getAllNotes() {
		ArrayList<SingleNote> result = new ArrayList<SingleNote>();

		DbAdapter dbAdapter = new DbAdapter(this);
		dbAdapter.open();

		result = dbAdapter.getAllNotesByContact(contactId);

		dbAdapter.close();
		return result;
	}

	private void refreshListView() {
		mListAdapter.setListData(getAllNotes());
		mListAdapter.notifyDataSetChanged();
	}

	public void log(String msg) {
		if (DBG) {
			Log.d(TAG, msg);
		}
	}
}
